package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * /用户下单
 * /@param orders
 * /@return
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private UserService userService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        log.info("订单数据：{}", orders);
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    /*
     * 分页
     * */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, LocalDateTime beginTime, LocalDateTime endTime) {
        Page<Orders> page1 = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(number != null, Orders::getNumber, number);
        lqw.between(beginTime != null && endTime != null, Orders::getOrderTime, beginTime, endTime);
        lqw.orderByDesc(Orders::getOrderTime);
        ordersService.page(page1, lqw);
        List<Orders> records = page1.getRecords();
        List<Orders> list = records.stream().map((item) -> {
            item.setUserName(item.getConsignee());
            return item;
        }).collect(Collectors.toList());
        page1.setRecords(list);
        return R.success(page1);
    }

    @PutMapping
    public R<String> put(@RequestBody Orders orders) {
        Orders orders1 = ordersService.getById(orders);
        orders1.setStatus(orders1.getStatus());
        ordersService.updateById(orders);
        return R.success("已处理");
    }

    /*
     * 历史订单
     * */
    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize) {
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Orders::getUserId,BaseContext.getCurrentId());
        Page<Orders> page1 = ordersService.page(ordersPage, lqw);
        return R.success(page1);
    }
}

